package com.yaorange.jk.web.sysadmin;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ModelDriven;
import com.yaorange.jk.entity.Dept;
import com.yaorange.jk.entity.Role;
import com.yaorange.jk.entity.User;
import com.yaorange.jk.service.DeptService;
import com.yaorange.jk.service.RoleService;
import com.yaorange.jk.service.UserService;
import com.yaorange.jk.utils.Encrypt;
import com.yaorange.jk.utils.MailUtils;
import com.yaorange.jk.utils.Pagination;
import com.yaorange.jk.web.BaseAction;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.MailSender;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.util.List;
import java.util.Set;
import java.util.UUID;

/**
 * @author coach tam
 * @date 2017/11/1
 */
public class UserAction extends BaseAction implements ModelDriven<User> {

    private static Logger logger = Logger.getLogger(UserAction.class);
    /**
     * 因为模型驱动需要实现getModel，然后我们把这个对象传递给jsp 需要单独弄一个get方法。
     * 所以，我们把名字改成model，一个getModel 就搞定了。
     */
    private User model = new User();

    //分页对象
    private Pagination page = new Pagination();
    //部门列表
    private List<Dept> deptList;
    //用户列表
    private List<User> userList;
    //角色列表
    private List<Role> roleList;

    //当前用户角色字符串
    private String userRoleStr;

    //所选角色id
    private String[] roleIds;
    @Autowired
    private UserService userService;

    @Autowired
    private DeptService deptService;

    @Autowired
    private RoleService roleService;

    @Autowired
    private SimpleMailMessage message;

    @Autowired
    private JavaMailSender sender;

    /**
     * 分页查询
     */
    public String list() {
        page = userService.findPage(page.getPageNo(), page.getPageSize());
        page.setUrl("userAction_list");
        push(page);
        return "list";
    }

    /**
     * 跳转添加页面
     */
    public String tocreate() {
        deptList = deptService.findAll();
        userList = userService.findAll();
        return "tocreate";
    }

    /**
     * 添加
     */
    public String insert() throws MessagingException {
        //设置新增用户 的 添加人，及添加人所属部门
        model.setCreateBy(getUser().getId());
        model.setCreateDept(getUser().getDept().getId());
        //初始化新增用户密码 （默认为 用户名）
        String pwd = Encrypt.md5(model.getUserName(), model.getUserName());
        model.setPassword(pwd);
        String active_code = UUID.randomUUID().toString();
        model.getUserInfo().setCode(active_code);
        userService.save(model);
        String active_text = "<a href='http://localhost:88/sysadmin/userAction_active?userInfo.code="+active_code+"&id="+model.getId()+"'>点击激活</a>";
        String email = model.getUserInfo().getEmail().toString().trim();
        //使用原生API发邮件
        //MailUtils.sendMail(email,"欢迎加入本公司！","测试成功:"+active_text);
        logger.info("开始发送邮件....");

        MimeMessage message = sender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message,true);
        helper.setFrom("javamail_wangwei@sina.com");
        //helper.setTo("1655857997@qq.com");
        helper.setTo(email);
        helper.setSubject("欢迎加入本公司！");
        helper.setText(active_text,true);//true,表示发送的是html 正文
        sender.send(message);

//        message.setTo(email);
//        message.setSubject("欢迎加入本公司！");
//        message.setText(active_text);
//        MailSender sen = sender;
//        sen.send(message);
        logger.info("邮件发送完成");
        return "rlist";
    }

    public String active(){
        model = userService.active(model);
        if(model==null){
            ActionContext.getContext().getValueStack().set("errorMsg","激活失败！");
        }else{
            ActionContext.getContext().getValueStack().set("errorMsg","激活成功，请登录！");
        }
        return "login";
    }

    /**
     * 跳转更新页面
     * @return
     */
    public String toupdate() {
        //根据id查询部门老数据
        model = userService.findById(model.getId());
        //存入栈顶
        push(model);

        deptList = deptService.findAll();
        return "toupdate";
    }

    /**
     *更新
     */
    public String update() {
        userService.update(model);
        return "rlist";
    }

    /**
     * 批量删除
     */
    public String delete() {
        String[] ids = model.getId().split(", ");
        userService.deleteByIds(ids);
        return "rlist";
    }

    public String toview(){
        model = userService.findById(model.getId());
        push(model);
        return "toview";
    }

    public String torole(){
        //所有的角色列表
        roleList = roleService.findAll();
        //当前用户角色 字符串  "r1,r2,r3,"
        model = userService.findById(model.getId());

        push(model);
        //查询当前用户角色
        Set<Role> roleSet = model.getRoleSet();
        StringBuilder sb = new StringBuilder();
        for (Role role:roleSet) {
            sb.append(role.getName()).append(",");
        }
        userRoleStr = sb.toString();
        return "torole";
    }


    public String role(){
        userService.updateRole(model.getId(),roleIds);

        return "rlist";
    }


    public List<Dept> getDeptList() {
        return deptList;
    }

    public void setPage(Pagination page) {
        this.page = page;
    }

    public List<User> getUserList() {
        return userList;
    }

    public List<Role> getRoleList() {
        return roleList;
    }

    public String getUserRoleStr() {
        return userRoleStr;
    }

    public void setRoleIds(String[] roleIds) {
        this.roleIds = roleIds;
    }

    @Override
    public User getModel() {
        return model;
    }
}
